import { IUserService, User } from "src/business/models/user";
import { Ref, getObject, log, Role } from "pao-aop";
import { CookieUtil } from "pao-aop-client";
import { ICompanyTemplateSignService, CompanySign } from "src/models/companySign";
import { COOKIE_KEY_CURRENT_USER, COOKIE_KEY_USER_ROLE } from "src/business/mainForm/backstageManageMainForm";

/** Cookie关键字：当前用户企业标识 */
export const COOKIE_KEY_COMPANY_ID = "__company_sign__";

/**
 * 工业互联网应用存储
 */
export class IndustryInternetSignAppStorage {

    /** 用户服务 */
    static userService_Fac?: Ref<IUserService>;
    /** 用户服务 */
    static get userService() {
        return getObject(IndustryInternetSignAppStorage.userService_Fac);
    }
    static companyTemplateSignService_Fac?: Ref<ICompanyTemplateSignService>;
    /** 企业服务 */
    static get companyTemplateSignService() {
        return getObject(IndustryInternetSignAppStorage.companyTemplateSignService_Fac);
    }
    /** 处理全局数据事件 */
    static async handleGlobalDataEvent() {
        try {
            const currentUser = await IndustryInternetSignAppStorage
                .userService!
                .get_current_user!()!;
            CookieUtil.save(COOKIE_KEY_CURRENT_USER, currentUser!);
            const roles = await IndustryInternetSignAppStorage
                .userService!
                .get_current_role!()!;
            CookieUtil.save(COOKIE_KEY_USER_ROLE, roles!);
            console.log('roles', roles!);
            const companySign = await IndustryInternetSignAppStorage
                .companyTemplateSignService!
                .get_current_user_company_sign!()!;
            console.log('companySign', companySign);
            CookieUtil.save(COOKIE_KEY_COMPANY_ID, companySign && companySign.id ? { 'id': companySign!.id, 'handle_code': companySign!.handle_code, 'handle_name': companySign!.handle_name } : {});
        } catch (error) {
            log('IndustryInternetSignAppStorage', `${error.message}`);
        }
    }
    /** 获取当前用户角色 */
    static getCurrentUserRoles() {
        return CookieUtil.read<Role[]>(COOKIE_KEY_USER_ROLE);
    }

    /** 获取当前用户企业标识 */
    static getCurrentCompanySign() {
        return CookieUtil.read<CompanySign>(COOKIE_KEY_COMPANY_ID);
    }

    /** 获取用户信息 */
    static getCurrentUser() {
        return CookieUtil.read<User>(COOKIE_KEY_CURRENT_USER);
    }
}